@file:Suppress("DEPRECATION")

package com.boyou.sytzc.ui

import android.app.Activity
import android.app.ProgressDialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import androidx.activity.viewModels
import com.boyou.sytzc.R
import com.boyou.sytzc.api.vmodel.HttpApiViewModel
import com.boyou.sytzc.ui.adapter.ServerLocalListAdapter
import com.boyou.sytzc.data.entity.ServerLocalInfoEntity
import com.boyou.sytzc.databinding.ActivitySettingsBinding
import com.boyou.sytzc.core.appctx.AppApplication
import com.boyou.sytzc.core.dialog.PasswordConfirmDialog
import com.boyou.sytzc.core.listener.OnChangeConfigListener
import com.boyou.sytzc.utils.app.AppConfig
import com.hi.dhl.binding.viewbind
import com.yuge.yugecse.ext.uibasic.BasicActivity
import com.yuge.yugecse.util.device.ToastUtil

/**
 * 设置页面
 */
class SettingsActivity : BasicActivity() {

    private val binding by viewbind<ActivitySettingsBinding>()

    private val networkViewModel by viewModels<HttpApiViewModel>()

    private val appConfig: AppConfig by lazy { AppConfig.singleton() } //配置相关辅助对象

    private var isDeviceChanged = false //设备号是否改变过

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(binding) {
            setSupportActionBar(toolbar.apply { title = "" })
            toolbar.setNavigationOnClickListener {
                if (isDeviceChanged)
                    setResult(Activity.RESULT_OK)
                finish()
            }
            val deviceNo = AppApplication.deviceNoManager.deviceNo
            if (!TextUtils.isEmpty(deviceNo)) etDeviceNo.setText(deviceNo)
            etInterfaceAddr.setText(appConfig.serverUrl)
            etHandleTimeSpan.setText(appConfig.handleTimeSpan.toString())
            etAutoTimeSpan.setText(appConfig.autoTimeSpan.toString())
            etGeoTime.setText(appConfig.geoSpacingTime.toString())
            imageSwitcher.isChecked = appConfig.allowDeleteImages
            rgMode.check(if (appConfig.locationMode == 0) R.id.rb_extract else R.id.rb_gps)
            rgMode.setOnCheckedChangeListener { _, _ ->
                etGeoTime.setText(AppConfig.singleton().geoSpacingTime.toString())
            }
            btnChooseServerLocal.setOnClickListener { onViewClick(it) }
            btnSaveAll.setOnClickListener { onViewClick(it) }
        }
    }

    private fun onViewClick(view: View) {
        when (view.id) {
            R.id.btnChooseServerLocal -> {
                val deviceNo = binding.etDeviceNo.text.toString().trim()
                if (deviceNo.isEmpty()) {
                    ToastUtil.showGenericToast(this, "请输入设备号")
                    return
                }
                getServerLocals(deviceNo) //获取服务器地址
            }
            R.id.btnSaveAll -> submitAllChangedData()
        }
    }

    /** 提交所有的配置数据 **/
    private fun submitAllChangedData() {
        val deviceNo = binding.etDeviceNo.text.toString().trim().trim('-', ' ')
        if (TextUtils.isEmpty(deviceNo)) {
            ToastUtil.showGenericToast(this, "请输入正确的设备号")
            return
        }
        val interfaceAddr = binding.etInterfaceAddr.text.toString()
        if (TextUtils.isEmpty(interfaceAddr)) {
            ToastUtil.showGenericToast(this, "请输入数据传输地址")
            return
        }
        val geoSpanTime = binding.etGeoTime.text.toString()
        if (TextUtils.isEmpty(geoSpanTime) || !geoSpanTime.matches("^\\d+$".toRegex())) {
            ToastUtil.showGenericToast(this, "请输入位置坐标搜集时间间隔")
            return
        }
        val handleTime = binding.etHandleTimeSpan.text.toString()
        if (TextUtils.isEmpty(handleTime) || !handleTime.matches("^\\d+$".toRegex())) {
            ToastUtil.showGenericToast(this, "请输入手动拍照时的时间间隔")
            return
        }
        val autoTime = binding.etAutoTimeSpan.text.toString()
        if (TextUtils.isEmpty(autoTime) || !autoTime.matches("^\\d+$".toRegex())) {
            ToastUtil.showGenericToast(this, "请输入自动拍照时的时间间隔")
            return
        }
        showChangeConfigTipDialog {
            AppApplication.deviceNoManager.deviceNo = deviceNo
            appConfig.serverUrl = interfaceAddr
            appConfig.handleTimeSpan = Integer.valueOf(handleTime)
            appConfig.autoTimeSpan = Integer.valueOf(autoTime)
            appConfig.locationMode =
                if (binding.rgMode.checkedRadioButtonId == R.id.rb_extract) 0 else 1
            appConfig.geoSpacingTime = geoSpanTime.toInt()
            appConfig.allowDeleteImages = binding.imageSwitcher.isChecked
            ToastUtil.showGenericToast(this, "修改成功")
            setResult(Activity.RESULT_OK)
            finish()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            if (isDeviceChanged)
                this.setResult(Activity.RESULT_OK)
            this.finish()
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 修改域名的提示弹窗
     */
    private fun showChangeConfigTipDialog(listener: OnChangeConfigListener?) =
        with(PasswordConfirmDialog()) {
            onPasswordVerifyListener =
                PasswordConfirmDialog.OnPasswordVerifyListener { listener?.onSuccess() }
            show(supportFragmentManager)
        }

    /**
     * 获取服务器地址列表
     * @param deviceNo 真实的服务器地址
     */
    @Suppress("DEPRECATION")
    private fun getServerLocals(deviceNo: String?) {
        val dialog = ProgressDialog(this).apply {
            setMessage("正在获取...")
            show()
        }
        networkViewModel.getServerLocals(1, deviceNo) { isSuccessful, message, result ->
            if (dialog.isShowing) dialog.dismiss()
            if (isSuccessful && !result.isNullOrEmpty())
                showServerLocalsSelectorDialog(result)
            if (!TextUtils.isEmpty(message))
                ToastUtil.showGenericToast(this, message)
        }
    }

    /**
     * 显示服务器地址选择对话框
     * @param result 服务器对话框列表数据
     */
    private fun showServerLocalsSelectorDialog(result: List<ServerLocalInfoEntity>) {
        val adapter = ServerLocalListAdapter(this, result.toMutableList())
        AlertDialog.Builder(this)
            .setTitle("请选择服务器地址")
            .setAdapter(adapter, null)
            .setPositiveButton("确定") { _, _ ->
                if (adapter.checkedItem == null) {
                    ToastUtil.showGenericToast(this, "请选择服务器地址")
                    return@setPositiveButton
                }
                binding.etInterfaceAddr.setText(adapter.checkedItem?.url)
            }
            .setNegativeButton("取消", null)
            .create()
            .show()
    }

}
